package service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import pojo.UserInfo;

import java.util.ArrayList;
import java.util.List;

public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据前端传来的用户名查询数据库
        UserInfo userInfo = findByUserName(username);
        //拥有的角色和权限的集合
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        //查询拥有的角色并添加到集合
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        grantedAuthorityList.add(authority);
        //查询拥有的权限并添加到集合
        authority = new SimpleGrantedAuthority("add");
        grantedAuthorityList.add(authority);
        //将securitiy需要的用户信息添加的USER对象并返回
        User user = new User(username,userInfo.getPassword(),grantedAuthorityList);
        return user;
    }



    public UserInfo findByUserName(String username){
        if("kang".equals(username)){
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername("kang");
            userInfo.setPassword("{noop}6666");
            return userInfo;
        }
        return null;
    }

    //密码加密
    public static void main(String []args){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println(encoder.encode("6666"));
    }
}
